#!/bin/bash

GUI_APP=Finder
IDENTIFIER="{{.identifier}}"

dialog() {
    ICON="$1"
    shift
    osascript -e "tell app \"$GUI_APP\" to activate" \
        -e "tell app \"$GUI_APP\" to display dialog \"$@\" \
            buttons \"Close\" default button 1 \
            with icon $ICON"
}

die() {
    echo "error: $@" >&2
    dialog stop "$@"
    exit 1
}

if [ "$(id -u)" -ne 0 ]; then
    cmd=$(printf "%q" "$0")
    osascript -- - "$cmd" <<EOF
on run argv
    do shell script item 1 of argv with administrator privileges with prompt "{{.BeatName | title}} uninstaller"
end run
EOF
    exit 0
fi

which -s pkgutil || die "pkgutil not available. Install XCode"

LINK="/Library/LaunchDaemons/$IDENTIFIER.plist"
if [ -e "$LINK" ]; then
    launchctl unload -w "$LINK"
    rm "$LINK"
fi

pkgutil --pkg-info "$IDENTIFIER" > /dev/null || die "{{.BeatName}} not installed"

for key in volume location
do
   EXP="^$key: "
   VAL=$(pkgutil --pkg-info "$IDENTIFIER" | grep "$EXP" | sed "s/$EXP//")
   eval $key=\$VAL
done

BASE="$volume$location"

test -d "$BASE" || die "Resolved base directory '$BASE' doesn't exist"

pushd "$BASE"
pkgutil --only-files --files "$IDENTIFIER" | tr '\n' '\0' | xargs -0 -n 1 rm
pkgutil --only-dirs --files "$IDENTIFIER" | sort -r | tr '\n' '\0' | xargs -0 -n 1 rmdir
popd

pkgutil --forget "$IDENTIFIER" || die "Failed to remove the package from the database"

# Cleanup runtime files like 'data/' and 'logs/'
BEAT_DIR="{{.install_path}}/{{.Vendor}}/{{.BeatName}}"
if [ -d "$BEAT_DIR" -a -n "{{.BeatName}}" -a -n "{{.Vendor}}" ]; then
    rm -rf "$BEAT_DIR"
fi

dialog note '{{.BeatName | title}} successfully uninstalled'
